package com.jinsilu.freight.ui.activity;

import android.app.Activity;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.exception.ResultException;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.common.MyVBActivity;
import com.jinsilu.freight.databinding.ActivityUploadIdCardBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.ShowImageHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.GetIdCardApi;
import com.jinsilu.freight.http.request.OCRApi;
import com.jinsilu.freight.http.request.UpdateImageApi;
import com.jinsilu.freight.http.request.VerifyIdCardApi;
import com.jinsilu.freight.http.response.FileBean;
import com.jinsilu.freight.http.response.IdCardBean;
import com.jinsilu.freight.http.response.OCRIDCardBean;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.dialog.DateDialog;
import com.jinsilu.freight.ui.dialog.MenuDialog;
import com.wildma.idcardcamera.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传身份证
 *
 * @author yangyang
 * @time 2020-11-11 17:35
 */
public class UploadIdCardActivity extends MyVBActivity<ActivityUploadIdCardBinding> {

    private final String TAG = getClass().getName();
    private int mCurrentSelectIndex; // 当前选择上传的图片条目索引
    private String frontImage;
    private String backImage;
    private List<String> mMenuDialogDataList;

    private IdCardBean mIdCardBean;

    @Override
    protected void initView() {
//        binding.tvNotificationTips.setVisibility(View.VISIBLE);
//        binding.tvNotificationTips.setText("拍摄图片时，请保持画面文字的清晰。");

        setOnClickListener(binding.tvExpirationDate, binding.ivIdCardFront, binding.ivIdCardBack, binding.tvBtnSubmitCertificate);
    }

    @Override
    protected void initData() {
        getIdCardStatus();
        initMenuDialogData();
        initStep();
    }

    private void initStep() {
        binding.layoutCertification.tvCertificationTips.setText("请使用本人身份信息进行认证，若使用他人身份认证并接单，将造成运费无法提现");
        binding.tvCheckTheInformation.setText(Html.fromHtml(getString(R.string.tips_check_the_information)));
        binding.layoutCertification.stepView.done(false);
        binding.layoutCertification.stepView.go(MTLConstants.STEP_ONE, true);
    }

    private void initMenuDialogData() {
        mMenuDialogDataList = new ArrayList<>();
        mMenuDialogDataList.add("相机");
        mMenuDialogDataList.add("相册");
    }

    /**
     * 获取身份验证状态
     */
    private void getIdCardStatus() {
        EasyHttp.get(this)
                .api(new GetIdCardApi())
                .request(new HttpCallback<HttpData<IdCardBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<IdCardBean> data) {
                        mIdCardBean = data.getData();
                        setCertificateStatus(mIdCardBean);
                    }
                });
    }

    private void setCertificateStatus(IdCardBean idCardBean) {
        // -2---未认证，-1---待审核，0---失败，1---成功
        switch (idCardBean.getIdCardCertificationStatus()) {
            case -2: // 未认证
                break;
            case 0: // 认证失败
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_rejected_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核未通过");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                binding.layoutCertification.tvCertificationTips.setText(TextUtils.isEmpty(idCardBean.getOpinion()) ? "" : idCardBean.getOpinion());
                setContentData(idCardBean);
                break;
            case 1: // 认证成功
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核通过");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approved));
                setContentData(idCardBean);
                break;
            case -1: // 提交全部认证资料 认证中
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approving_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核中");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approving));
                setContentData(idCardBean);
                break;
            default:
                break;
        }
    }

    /**
     * 设置不允许点击
     */
    private void disableClicked(String tips) {
        binding.ivIdCardFront.setEnabled(false);
        binding.ivIdCardBack.setEnabled(false);
        binding.etUserName.setEnabled(false);
        binding.etIdCardNumber.setEnabled(false);
        binding.tvExpirationDate.setEnabled(false);

        binding.layoutCertification.stepView.done(true);

        binding.layoutCertification.tvCompleteCanTakeOrder.setText(tips);
        binding.layoutCertification.tvCertificationTips.setVisibility(View.GONE);

        binding.tvIdCardFrontTips.setVisibility(View.GONE);
        binding.tvIdCardBackTips.setVisibility(View.GONE);
    }

    /**
     * 数据回填
     *
     * @param idCardBean 身份数据
     */
    private void setContentData(IdCardBean idCardBean) {
        frontImage = idCardBean.getIdCardFrontUrl();
        backImage = idCardBean.getIdCardReverseUrl();
        if (!TextUtils.isEmpty(frontImage))
            ShowImageHelper.showNormal(this, idCardBean.getIdCardFrontUrl(), binding.ivIdCardFront);
        if (!TextUtils.isEmpty(backImage))
            ShowImageHelper.showNormal(this, idCardBean.getIdCardReverseUrl(), binding.ivIdCardBack);

        binding.etUserName.setText(idCardBean.getName());
        binding.etIdCardNumber.setText(idCardBean.getIdCard());
        binding.tvExpirationDate.setText(idCardBean.getValidityEndDate());
        binding.tvBtnSubmitCertificate.setEnabled(true);
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        if (v == binding.tvExpirationDate) {
            showDateDialog();
        } else if (v == binding.ivIdCardFront) {
            showTipsDialog();
            mCurrentSelectIndex = 0;
//            showMenuDialog();
//            startImageSelectActivity(0);
        } else if (v == binding.ivIdCardBack) {
            showTipsDialog();
            mCurrentSelectIndex = 1;
//            startImageSelectActivity(1);
//            showMenuDialog();
        } else if (v == binding.tvBtnSubmitCertificate) {
            if (null == mIdCardBean) {
                toast(R.string.error_certification_failed_with_network);
                return;
            }
            switch (mIdCardBean.getIdCardCertificationStatus()) {
                // -2---未认证，-1---待审核，0---失败，1---成功
                case -2: // 未认证
                case 0: // 认证失败
                    submitInfo();
                    break;
                case -1: // -待审核
                case 1: // 认证成功
                    toNextSteps();
                    break;
                default:
                    break;
            }
        }
    }

    private void toNextSteps() {
        startActivity(UploadDrivingLicenseActivity.class);
    }

    private BaseDialog tipsDialog;

    private void showTipsDialog() {
        // 自定义对话框
        if (null == tipsDialog) {
            tipsDialog = new BaseDialog.Builder(this)
                    .setContentView(R.layout.dialog_certificate_tips)
                    .setAnimStyle(BaseDialog.ANIM_SCALE)
                    //.setText(id, "我是预设置的文本")
                    .setGravity(Gravity.BOTTOM)
                    .setOnClickListener(R.id.tv_know, (BaseDialog.OnClickListener<TextView>) (dialog, view) ->
                            {
//                                showMenuDialog();
                                startImageSelectActivity(mCurrentSelectIndex);
                                dialog.dismiss();
                            }

                    )
                    .show();
        } else {
            tipsDialog.show();
        }
    }

    private BaseDialog menuDialog;

    private void showMenuDialog() {
        if (null == menuDialog) {
            menuDialog = new MenuDialog.Builder(this)
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setList(mMenuDialogDataList)
                    .setListener(new MenuDialog.OnListener<String>() {

                        @Override
                        public void onSelected(BaseDialog dialog, int position, String string) {
                            if (MTLConstants.PHOTO == position) {
                                if (0 == mCurrentSelectIndex) {
//                                    IDCardCamera.create(UploadIdCardActivity.this).openCamera(IDCardCamera.TYPE_IDCARD_FRONT);
                                } else if (1 == mCurrentSelectIndex) {
//                                    IDCardCamera.create(UploadIdCardActivity.this).openCamera(IDCardCamera.TYPE_IDCARD_BACK);
                                }
                            } else if (MTLConstants.ALBUM == position) {
//                                PictureSelectorHelper.showPicSelector(UploadIdCardActivity.this, new MyResultCallback());
                            }
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    })
                    .show();
        } else {
            menuDialog.show();
        }
    }

    /**
     * 身份验证
     */
    private void submitInfo() {
        if (TextUtils.isEmpty(frontImage)) {
            toast("请上传身份证正面");
            return;
        }
        if (TextUtils.isEmpty(backImage)) {
            toast("请上传身份证背面");
            return;
        }
        String name = binding.etUserName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            toast("请输入姓名");
            return;
        }
        // 新疆中文姓名
        String REGEX_ZH_XJ = "^[\\u4e00-\\u9fa5]+·[\\u4e00-\\u9fa5]+$";
        if (!RegexUtils.isZh(name) && !RegexUtils.isMatch(REGEX_ZH_XJ, name)) {
            toast("姓名须是汉字");
            return;
        }
        String idNumber = binding.etIdCardNumber.getText().toString().trim();
        if (TextUtils.isEmpty(idNumber)) {
            toast("请输入身份证号");
            return;
        }
        if (!RegexUtils.isIDCard15(idNumber) && !RegexUtils.isIDCard18Exact(idNumber)) {
            toast("请确认身份证号是否正确");
            return;
        }
        String validate = binding.tvExpirationDate.getText().toString().trim();
        if (TextUtils.isEmpty(validate)) {
            toast("请选择有效期止");
            return;
        }

        EasyHttp.post(this)
                .api(new VerifyIdCardApi()
                        .setIdCardFrontUrl(frontImage)
                        .setIdCardReverseUrl(backImage)
                        .setIdCard(idNumber)
                        .setAddress(mIdCardBean.getAddress())
                        .setBirthday(mIdCardBean.getBirthday())
                        .setName(name)
                        .setNation(mIdCardBean.getNation())
                        .setValidityStartDate(mIdCardBean.getValidityStartDate())
                        .setValidityEndDate(validate)
                )
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
//                        setResult(RESULT_OK);
//                        finish();
                        toNextSteps();
                    }

                    @Override
                    public void onFail(Exception e) {
                        CommonHelper.toastErrorMsg(e, getString(R.string.plz_reupload_id_card_image));
                    }
                });
    }

    /**
     * 返回结果回调
     */
//    private class MyResultCallback implements OnResultCallbackListener<LocalMedia> {
//
//        @Override
//        public void onResult(List<LocalMedia> result) {
//            for (LocalMedia media : result) {
//                Log.i(TAG, "是否压缩:" + media.isCompressed());
//                Log.i(TAG, "压缩:" + media.getCompressPath());
//                Log.i(TAG, "原图:" + media.getPath());
//                Log.i(TAG, "绝对路径:" + media.getRealPath());
//                Log.i(TAG, "是否裁剪:" + media.isCut());
//                Log.i(TAG, "裁剪:" + media.getCutPath());
//                Log.i(TAG, "是否开启原图:" + media.isOriginal());
//                Log.i(TAG, "原图路径:" + media.getOriginalPath());
//                Log.i(TAG, "Android Q 特有Path:" + media.getAndroidQToPath());
//                Log.i(TAG, "宽高: " + media.getWidth() + "x" + media.getHeight());
//                Log.i(TAG, "Size: " + media.getSize());
//                // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，如旋转角度、经纬度等信息
//                uploadImage(new File(media.getCutPath()));
//            }
//        }
//
//        @Override
//        public void onCancel() {
//            Log.i(TAG, "PictureSelector Cancel");
//        }
//    }

    /**
     * 启动图片选择
     */
    private void startImageSelectActivity(int index) {
        ImageSelectVBActivity.start(this, 1, index, new ImageSelectVBActivity.OnPhotoSelectListener() {

            @Override
            public void onSelected(File file) {
                uploadImage(file);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void uploadImage(File file) {
        // 上传头像
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImage(file))
                .request(new HttpCallback<HttpData<FileBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<FileBean> data) {
//                        FileUtils.delete(file);
                        // 删除身份证拍照缓存
                        FileUtils.clearCache(UploadIdCardActivity.this);
                        String imgUrl = data.getData().getUrl();
                        if (mCurrentSelectIndex == 0) {
                            ocr(MTLConstants.ID_FRONT, imgUrl);
//                            frontImage = imgUrl;
//                            ShowImageHelper.showNormal(UploadIdCardActivity.this, imgUrl, binding.ivIdCardFront);
                        } else {
                            ocr(MTLConstants.ID_BACK, imgUrl);
//                            backImage = imgUrl;
//                            ShowImageHelper.showNormal(UploadIdCardActivity.this, imgUrl, binding.ivIdCardBack);
                        }
                    }
                });
    }

    /**
     * orc 识别
     *
     * @param type   类型【1身份证人像面；2身份证国徽面；3驾驶证正页；4驾驶证副页；5行驶证正页；6行驶证副页；7车辆道路运输证】
     * @param imgUrl 图片地址
     */
    private void ocr(String type, String imgUrl) {
        EasyHttp.post(this)
                .api(new OCRApi()
                        .setType(type)
                        .setUrl(imgUrl)
                )
                .request(new HttpCallback<HttpData<OCRIDCardBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<OCRIDCardBean> data) {
                        OCRIDCardBean ocridCardBean = data.getData();
                        if (ObjectUtils.isEmpty(ocridCardBean)) {
                            toast(R.string.plz_reupload_id_card_image);
                            return;
                        }
                        if (mCurrentSelectIndex == 0) {
                            mIdCardBean.setIdCardFrontUrl(imgUrl);
                            mIdCardBean.setAddress(ocridCardBean.getAddress());
                            mIdCardBean.setBirthday(ocridCardBean.getBirth());
                            mIdCardBean.setIdCard(ocridCardBean.getNumber());
                            mIdCardBean.setName(ocridCardBean.getName());
                            mIdCardBean.setNation(ocridCardBean.getEthnicity());
                        } else {
                            mIdCardBean.setIdCardReverseUrl(imgUrl);
                            mIdCardBean.setValidityStartDate(ocridCardBean.getValidFrom());
                            if (MTLConstants.LONG_TIME.equals(ocridCardBean.getValidTo())) { // @dsz @wyh
                                mIdCardBean.setValidityEndDate(MTLConstants.LONG_TIME_DEFAULT);
                            } else {
                                mIdCardBean.setValidityEndDate(ocridCardBean.getValidTo());
                            }
//                            mIdCardBean.setValidityEndDate(ocridCardBean.getValidTo());
                        }
                        setContentData(mIdCardBean);
                    }

                    @Override
                    public void onFail(Exception e) {
                        toast(R.string.plz_reupload_id_card_image);
                    }
                });
    }

    private BaseDialog expirationDialog;

    private void showDateDialog() {
        // 日期选择对话框
        if (null == expirationDialog) {
            expirationDialog = new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置日期
                    //.setDate("2018-12-31")
                    //.setDate("20181231")
                    //.setDate(1546263036137)
                    // 设置年份
                    //.setYear(2018)
                    // 设置月份
                    //.setMonth(2)
                    // 设置天数
                    //.setDay(20)
                    // 不选择天数
                    //.setIgnoreDay()
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
//                            toast(year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day));
                            // 如果不指定时分秒则默认为现在的时间
//                            Calendar calendar = Calendar.getInstance();
//                            calendar.set(Calendar.YEAR, year);
                            // 月份从零开始，所以需要减 1
//                            calendar.set(Calendar.MONTH, month - 1);
//                            calendar.set(Calendar.DAY_OF_MONTH, day);
//                            toast("时间戳：" + calendar.getTimeInMillis());
                            //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                            binding.tvExpirationDate.setText(String.format("%s-%s-%s", year, month, day));
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    })
                    .show();
        } else {
            expirationDialog.show();
        }
    }
}
